<template>
  <div class="event_config card_table">
    <header>
      <span class="o">配置面板</span>
      <span class="t">
        <span class="tool_top" @click="new_config">
          <i class="el-icon-refresh"></i>重置
        </span>
        <span class="tool_top" @click="queryMessage">
          <i class="el-icon-search"></i>查询
        </span>
      </span>
    </header>
    <section v-show="switch_bool">
      <!-- 指标 -->
      <div v-for="(_i,_in) in config.messures" :key="_i.eventId" class="messures_line">
        <div class="til valueTreeOne">
          <i
            @click="indexfoldingSelf(_i.eventId)"
            class="el-icon-arrow-right"
            :style="{transform:foldingSelfShow(_i.eventId)?'rotate(90deg)':'rotate(0deg)'}"
          ></i>
          <span class="icon">{{convert(_in+1)}}</span>
          <dropdownTrigger
            :activeItem="_i.field"
            @change="indexFieldChange($event,_i,_in)"
            @groupChange="configShowGroup"
            class="key flex_cen"
            :overallScreeningData="groupingData"
          ></dropdownTrigger>的
            <el-select  clearable class="key" size="small" filterable v-model="_i.aggregator" placeholder="指标目标值">
              <el-option
                v-for="item in index_value_list"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>

          <i class="el-icon-close toosl_one err" @click="config.messures.length>1?config.messures.splice(_in,1):null"></i>
          <span class="tools_one" @click="indexScreenFun(_i)">
            <i class="el-icon-search"></i>
            <span>筛选</span>
          </span>

          <span
            class="tools_one"
            @click="config.messures.splice(_in,0,{
             id: Math.random()
            .toString(36)
            .substr(2),
            filter:_i.filter,
            name: _i.name, // 指标显示名称
            field: _i.field, // 指标 key
            fieldArr:_i.fieldArr, // 根据field请求到筛选组件用到的第一列数据
            aggregator: _i.aggregator // 指标 value
          })"
          >
            <i class="el-icon-printer"></i>
            <span>复制</span>
          </span>

          <!-- <span class="tools_one" @click="drawer_bool=true;yj_index=_in">
            <i class="el-icon-bell"></i>
            <span>预警</span>
          </span>-->
        </div>
        <!-- 每条指标下的筛选 -->
        <div class="deep_screen" v-show="foldingSelfShow(_i.eventId)">
          <conditionScreening
            :key="updateNumScreen"
            :fieldArr="_i.fieldArr"
            @change="changeScreen($event,_i,_in)"
            :limit="2"
            deep="并且满足"
            add="条件新增"
            :ref="_i.eventId+'computedTree'"
            :filterEnter="_i.filter"
          ></conditionScreening>
        </div>
      </div>

      <div class="index_add" v-if="groupingData.length>0">
        <span @click="index_add">
          <i class="el-icon-circle-plus"></i>指标
        </span>
      </div>
      <!-- 全局筛选 -->
      <template v-if="fieldArrTotal.length>0">
        <conditionScreening
          :key="updateNumTotal"
          :limit="2"
          deep="并且满足"
          ref="computedTreeTotal"
          add="条件新增"
          @change="overallSituationScreen"
          :filterEnter="config.filter"
          :fieldArr="fieldArrTotal"
        ></conditionScreening>

        <div class="total_screen" @click="$refs.computedTreeTotal.initAdd()">
          <i class="el-icon-plus"></i>
          全局筛选
        </div>
      </template>
      <!-- 分组配置区域 -->
      <div class="group_cig" v-if="fieldArrTotal.length>0">
        <span class="txt">按</span>

        <dropdownTriggerLayered
          class="tags"
          v-for="(_i,_in) in config.byFields"
          :key="_i.value"
          @change="config.byFields.splice(_in, 1, $event)"
          @del="config.byFields.splice(_in,1)"
          :del="true"
          :group="true"
          :activeItemEnter="_i"
          :promptPanel="true"
          :overallScreeningData="fieldArrTotal"
        ></dropdownTriggerLayered>

        <span class="txt labelbox" :style="{position:'relative'}">
          <i class="el-icon-plus" @click="labelShowGroup"></i>

          <dropdownTriggerLayered
            :group="true"
            @change="groupScreenAdd($event)"
            :promptPanel="true"
            class="addGroup"
            ref="newaddgroup"
            :overallScreeningData="fieldArrTotal"
          ></dropdownTriggerLayered>分组
        </span>
      </div>
    </section>
    <footer class="no_copy" @click="switch_bool=!switch_bool">
      <span v-if="switch_bool">
        收起
        <i class="el-icon-arrow-up"></i>
      </span>
      <span v-else>
        展开
        <i class="el-icon-arrow-down"></i>
      </span>
    </footer>
    <groupEditing @change="queryEventGroup" ref="groupEditing"></groupEditing>
    <!-- 预警弹框 -->
    <el-drawer
      size="40%"
      title="新建预警"
      :modal="false"
      :visible.sync="drawer_bool"
      :with-header="false"
    >
      <div class="drawer_box">
        <header>
          <span class="til">新建预警</span>
          <i @click="drawer_bool = false" class="el-icon-close"></i>
        </header>
        <section>
          <div class="min_til section_til">基础信息</div>
          <div class="section_til">预警名称</div>
          <div class="el_com">
            <el-input clearable :size="table_size" class="el_inp" placeholder="请输入内容"></el-input>
          </div>
          <div class="section_til">备注</div>
          <div class="el_com">
            <el-input clearable :size="table_size" class="el_inp" placeholder="请输入内容"></el-input>
          </div>
          <div class="section_til">监控指标</div>
          <div class="el_com" v-if="config.messures&&config.messures[yj_index]">
            <!-- yj_index -->
            <el-cascader
              disabled
              size="small"
              class="key"
              :value="config.messures[yj_index].key"
              :options="[]"
            ></el-cascader>-
            <el-cascader
              size="small"
              disabled
              class="key"
              :value="config.messures[yj_index].value"
              :options="[]"
            ></el-cascader>
          </div>
          <div class="min_til section_til">触发配置</div>
          <div class="section_til">指标周期</div>
          <div class="el_com">
            <el-select
              :size="table_size"
              v-model="zhouqi"
              clearable
              class="el_inp el_small"
              placeholder="请选择"
            >
              <el-option
                v-for="item in [
                  {
                    value: 0,
                    label: '天'
                  }
                ]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
          <div class="section_til">监控时段</div>
          <div class="el_com">
            <el-select
              :size="table_size"
              clearable
              multiple
              v-model="shiduan_l"
              class="el_inp el_small"
              placeholder="请选择"
            >
              <el-option
                v-for="item in [
                  {
                    value: 0,
                    label: '周一'
                  }
                ]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-select
              v-if="zhouqi==1"
              :size="table_size"
              clearable
              multiple
              v-model="shiduan_r"
              class="el_inp el_small"
              placeholder="请选择"
            >
              <el-option
                v-for="item in [
                  {
                    value: 0,
                    label: '00:00-06:30'
                  }
                ]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
          <div class="section_til">触发规则</div>
          <div class="total_screen el_com">
            <i class="el-icon-plus"></i>
            添加规则
          </div>
          <div class="el_com">
            <el-table :data="[]" height="120" style="width: 100%">
              <el-table-column prop="date" label="分组"></el-table-column>
            </el-table>
          </div>
          <div class="min_til section_til">通知设置</div>
          <div class="section_til">发件地址</div>
          <div class="total_screen el_com">
            xxs@sensorsdata.cn
            <i style="marginLeft:10px" class="el-icon-s-tools"></i>
            测试发送
          </div>
          <div class="section_til">收件地址</div>
          <div class="el_com">
            <el-input clearable :size="table_size" class="el_inp" placeholder="请输入内容"></el-input>
          </div>
        </section>
        <footer>
          <!-- 编辑打开抽屉时，调用的函数 -->
          <el-button class="btn" @click="drawer_bool = false" size="mini" type="primary">保存</el-button>
          <el-button class="btn" @click="drawer_bool = false" size="mini" type="primary" plain>取消</el-button>
        </footer>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import conditionScreening from "@/components/conditionScreening/computedTree.vue";
import dropdownTrigger from "@/components/dropdownTrigger/index.vue";
import dropdownTriggerLayered from "@/components/dropdownTriggerLayered/index.vue";
import groupEditing from "@/components/groupEditing/index.vue"; // 引入事件分组管理组件
import analysisApi from "@/utils/api/analysisApi.js";

export default {
  name: "event_config",
  props: {
    config: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  watch: {
    config: {
      handler() {},
      deep: true
    }
  },
  components: {
    conditionScreening,
    groupEditing,
    dropdownTrigger,
    dropdownTriggerLayered
  },
  data() {
    return {
      index_value_list: [
        {
          value: "general",
          label: "总次数"
        },
        {
          value: "unique",
          label: "用户数"
        },
        {
          value: "average",
          label: "人均次数"
        }
      ], // 指标目标值
      foldingSelf: [],
      fieldArrTotal: [], // 全局筛选，第一列可选值数组
      updateNumTotal: 0, // 刷新变量 全局筛选
      updateNumScreen: 0, // 刷新变量 指标
      groupingData: [], // 事件分组
      shiduan_l: [],
      shiduan_r: [],
      zhouqi: null,
      yj_index: 0, // 预警下标
      drawer_bool: false, // 抽屉
      table_size: "medium",
      switch_bool: false // 是否展开
    };
  },
  methods: {
    // 查询触发函数
    queryMessage() {

      // 因为指标下的 事件id  (eventId)  不能做指标标识 所以追加拼接后的name 拼接后的标识id
      let indexValueObj = {};
      this.index_value_list.map(_i=>{
        indexValueObj[_i.value] = _i.label
      })
      let obj = JSON.parse(JSON.stringify(this.config));
      try{
        if(obj.messures){
          obj.messures.map(_i=>{
            _i.aggregatorName = indexValueObj[_i.aggregator];    // 事件属性名称追加
            _i.name = _i.eventName + '的' + indexValueObj[_i.aggregator]; // 指标名称凭借
            _i.echartId = _i.eventId + _i.aggregator;     // 指标标识拼接
          })
        }
      }catch(err){
        console.log('指标name处理异常',err)
      }
      this.$emit("query", obj);
    },
    // 指标折叠函数
    indexfoldingSelf(eventId, bool = false) {
      let _b = false;
      let _index = 0;
      this.foldingSelf.map((_i, _in) => {
        if (_i == eventId) {
          _b = true;
          _index = _in;
        }
      });
      if (bool) {
        if (!_b) {
          this.foldingSelf.push(eventId);
        }
      } else {
        if (_b) {
          this.foldingSelf.splice(_index, 1);
        } else {
          this.foldingSelf.push(eventId);
        }
      }
    },
    // 指标筛选显示判断函数
    foldingSelfShow(eventId) {
      let bool = false;
      this.foldingSelf.map(_i => {
        if (_i == eventId) {
          bool = true;
        }
      });
      return bool;
    },
    // 获取全局筛选下的第一列可选值
    async fieldArrTotalGet() {
      let res = await analysisApi.eventAnalysis.eventAnalysisPropertyList({
        eventId: ""
      });
      if (res.success) {
        let _arr = [];
        if (
          res.value.eventPropertyList &&
          res.value.eventPropertyList.length > 0
        ) {
          _arr.push({
            id: Math.random()
              .toString(36)
              .substr(2),
            name: "事件属性",
            children: res.value.eventPropertyList
          });
        }
        if (
          res.value.userPropertyList &&
          res.value.userPropertyList.length > 0
        ) {
          _arr.push({
            id: Math.random()
              .toString(36)
              .substr(2),
            name: "用户属性",
            children: res.value.userPropertyList
          });
        }
        this.fieldArrTotal = _arr;
      }
    },
    // 每条指标的筛选点击函数
    indexScreenFun(item) {
      try {
        if (item.fieldArr && item.fieldArr.length > 0) {
          this.$refs[item.eventId + "computedTree"][0].initAdd();
          this.indexfoldingSelf(item.eventId, true);
        } else {
          this.$message({
            message: "暂无当前指标属性组",
            type: "warning"
          });
        }
      } catch (err) {
        console.log(err, "错误");
      }
    },
    // 每条指标的 key 更改   查询指标切换后，筛选组件的第一列可选值
    async indexFieldChange(value, item, index) {
      try {
        let obj = JSON.parse(JSON.stringify(this.config.messures[index]));
        if (item.eventId == obj.eventId) {
          let obj = {
            field:value,
            aggregator:this.config.messures[index].aggregator,
            eventId:value.eventId,
            eventName:value.eventName,
            filter:null,
            fieldArr:[]
          }
          this.config.messures.splice(index,1,obj)
          this.updateNumScreen++;
          let res = await analysisApi.eventAnalysis.eventAnalysisPropertyList({
            eventId: value.eventId
          });
          if (res.success) {
            let _arr = [];
            if (
              res.value.eventPropertyList &&
              res.value.eventPropertyList.length > 0
            ) {
              _arr.push({
                id: Math.random()
                  .toString(36)
                  .substr(2),
                name: "事件属性",
                children: res.value.eventPropertyList
              });
            }
            if (
              res.value.userPropertyList &&
              res.value.userPropertyList.length > 0
            ) {
              _arr.push({
                id: Math.random()
                  .toString(36)
                  .substr(2),
                name: "用户属性",
                children: res.value.userPropertyList
              });
            }
            obj.fieldArr = _arr;
            this.config.messures.splice(index,1,obj)
            this.updateNumScreen++;
          }
        }
      } catch (err) {
        console.log(err, "指标获取错误");
      }
    },
    // 查询事件分组数据函数
    async queryEventGroup() {
      let res = await analysisApi.eventAnalysis.eventGroupQuery({
        appId: this.appId
      });
      if (res.success) {
        this.groupingData = res.value;
      } else {
        this.groupingData = [];
      }
    },
    labelShowGroup() {
      try {
        this.$refs.newaddgroup.panelBool_change();
      } catch (err) {
        console.log(err, "错误");
      }
    },
    // 打开事件分组组件
    configShowGroup() {
      try {
        this.$refs.groupEditing.showHidden(true);
      } catch (err) {
        console.log(err, "错误");
      }
    },
    overallSituationScreen(value) {
      this.config.filter = value;
    },
    changeScreen(value, item, index) {
      try {
        this.config.messures.map((_i, _in) => {
          if (_i.eventId == item.eventId && _in == index) {
            _i.filter = value;
          }
        });
      } catch (err) {
        console.log(err, "错误");
      }
    },
    convert(num) {
     return num <= 26
        ? String.fromCharCode(num + 64)
        : this.convert(~~((num - 1) / 26)) + this.convert(num % 26 || 26);
    },
    // 指标追加
    index_add() {
      this.config.messures.push({
        id: Math.random()
          .toString(36)
          .substr(2),
        filter: null, // 指标下的筛选
        name: null, // 指标显示名称
        field: null, // 指标 key
        fieldArr: [], // 根据field请求到筛选组件用到的第一列数据
        aggregator: null // 指标 value
      });
    },
    // 配置面板，新增分组函数
    groupScreenAdd(newValue) {
      let bool = false;
      console.log(newValue, "分组新增");
      this.config.byFields.map(_i => {
        if (_i.id == newValue.id) {
          bool = true;
        }
      });
      if (!bool) {
        console.log(123);
        this.config.byFields.push(newValue);
      }
    },
    // 配置面板重置函数
    new_config() {
      try {
        this.config.filter = null;
        this.config.byFields = [];
        this.config.messures = [];
        this.updateNumScreen++;
        this.updateNumTotal++;
      } catch (err) {
        this.$message({
          message: err,
          type: "warning"
        });
      }
    }
  },
  beforeCreate() {},
  created() {
    this.queryEventGroup();
    this.fieldArrTotalGet();
  },
  beforeMount() {},
  mounted() {},
  computed: {
    appId() {
      return this.$store.state.global.appId;
    }
  }
};
</script>

<style scoped lang="scss">
* {
  box-sizing: border-box;
}
.labelbox {
  display: inline-block;
  min-width: 2.6rem;
  margin: 0.2rem 0;
  height: 0.4rem;
}
::v-deep .el-input__inner{
  height: .52rem;
}
::v-deep .addGroup {
  border: none;
  left: -0.4rem;
  position: absolute;
  background: rgba($color: #01b27a, $alpha: 0);
  .activeItemCont {
    opacity: 0;
  }
}
::v-deep .addGroup:hover {
  border: none;
  box-shadow: none;
}
// 级联样式
.deep_screen .one_line:hover {
  background: rgba($color: #409eff, $alpha: 0.2);
}

.event_config::-webkit-scrollbar {
  display: none;
}
.event_config {
  header {
    width: 100%;
    height: 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 0 auto;
    cursor: pointer;
    box-sizing: border-box;
    .t {
      .tool_top {
        font-size: 14px;
        font-weight: 400;
        margin: 0 10px;
        i {
          margin: 0 6px;
        }
      }
      .tool_top:hover {
        color: #01b27a;
        // font-size: 14px;
        font-weight: 500;
      }
    }
  }
  footer {
    cursor: pointer;
    width: 100%;
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 6px auto 0;
    cursor: pointer;
    font-weight: 500;
    font-size: 10px;
    border-top: 1px solid #ebeef5;
    color: #303133;
    box-sizing: border-box;
    span {
      padding-right: 20px;
      i {
        margin: 0 10px;
      }
    }
  }
  footer:hover {
    color: #307ef2;
    font-weight: 500;
  }
  section {
    width: 100%;
    margin: 0 auto;
    cursor: pointer;
    box-sizing: border-box;
    // padding: 10px 0 0;
    // 指标筛选
    .index_add {
      width: 100%;
      padding: 0 0 10px 0.5%;
      margin: 0 auto 10px;
      height: 40px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ebeef5;
      span {
        margin-right: 0.6rem;
        i {
          font-weight: 800;
          font-size: 0.3rem;
          color: #00bf8a;
          margin: 0 10px 0 0;
        }
      }
    }
    .messures_line {
      width: 99%;
      margin: 0.1rem auto;
      min-height: 50px;
      border-radius: 4px;
      .til {
        display: flex;
        height: 50px;
        align-items: center;
        .el-icon-arrow-right {
          transition: all 0.5s ease;
        }
        .icon {
          width: 0.4rem;
          height: 0.4rem;
          background: #00bf8a;
          border-radius: 50%;
          color: white;
          margin: 0 0.2rem;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        .key {
          margin: 0 0.2rem;
          height: 0.52rem;
        }
        .tools_one {
          margin: 0 0.3rem;
        }
      }
      .deep_screen {
        width: 95%;
        margin-left: 5%;
      }
    }
    .messures_line:hover {
      background: rgba($color: #f2f6fc, $alpha: 0.9);
    }
    // 全局筛选
    .total_screen {
      padding: 10px 0;
      width: 99%;
      margin: 0 auto;
      height: 40px;
      display: flex;
      align-items: center;
      color: #307ef2;
      i {
        font-weight: 800;
        margin: 0 10px 0 0;
      }
    }
    // 分组区域
    .group_cig {
      border-top: 1px solid #ebeef5;
      padding: 10px 0;
      width: 100%;
      margin: 0 auto;
      .txt {
        cursor: pointer;
        position: relative;
        i {
          font-weight: 800;
          color: #307ef2;
          margin: 0 0.5rem;
        }
      }
      .tags {
        margin: 0.1rem 0.2rem;
      }
    }
  }
}

// 级联样式
.valueTreeOne {
  display: flex;
  align-items: center;
  border-radius: 4px;
  min-height: 46px;
  i {
    font-weight: 800;
    opacity: 0;
    margin: 0 0.05rem 0 0;
  }
  .tools_one {
    margin: 0 0.3rem 0 0;
    opacity: 0;
  }
  .tools_one:hover {
    color: #007aff;
    font-weight: 500;
  }
  .el-icon-arrow-right {
    opacity: 1;
  }
  .err:hover {
    color: red;
    // font-size: 16px;
  }
}
.valueTreeOne:hover {
  i,
  .tools_one {
    opacity: 1;
  }
}
// 抽屉壳子元素
.drawer_box {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  position: relative;
  header {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;
    padding: 0 20px 0 10px;
    border-bottom: 1px solid #e4e7ed;
    .til {
      font-family: "Helvetica Neue", Helvetica, "PingFang SC",
        "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
      font-size: 14px;
      font-weight: 600;
      color: rgba($color: #303133, $alpha: 1);
    }
    i {
      font-size: 16px;
      font-weight: 600;
      transition: all 0.5s ease;
    }
    i:hover {
      transform: rotate(90deg);
      font-size: 20px;
      font-weight: 800 !important;
    }
  }
  section::-webkit-scrollbar {
    display: none;
  }
  section {
    position: absolute;
    left: 0;
    right: 0;
    top: 60px;
    bottom: 66px;
    padding: 0 0 30px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-direction: column;
    overflow-y: scroll;
    .section_til {
      width: 100%;
      text-indent: 20px;
      height: 30px;
      line-height: 30px;
      text-align: left;
      color: #909399;
      font-size: 12px;
    }
    .min_til {
      font-size: 16px;
      text-indent: 10px;
      font-weight: 500;
      height: 40px;
      line-height: 40px;
      color: #606266;
    }
    .el_com {
      width: 100%;
      padding: 6px 0 6px 30px;
      // height: 60px;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      .el_inp {
        width: 80%;
        // transform: scale(1, 0.9);
      }
      .el_small {
        width: 45%;
        margin: 0 6px 0 0;
      }
      .lang {
        width: 90%;
        // min-width: 400px;
      }
    }
  }
  footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    height: 58px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 0 0;
    border-top: 1px solid #e4e7ed;
    .btn {
      margin: 0 20px;
    }
  }
}
</style>
